using System;
using System.Diagnostics.Contracts;
using System.Text;
using OpenWaves.Text;

namespace OpenWaves
{
    public partial class UrlPath
    {
        public static string GenerateSlug(string text)
        {
            Contract.Requires<ArgumentNullException>(String.IsNullOrEmpty(text) == false);
            Contract.Ensures(Contract.Result<string>() != null);

            const char separator = '-';

            var decodedPath = BestFitASCIIEncoding.Encode(text);

            var builder = new StringBuilder("", decodedPath.Length * 2);

            bool wasPreviousCharSeparator = false;
            foreach (char currentChar in decodedPath)
            {
                if (IsValidChar(currentChar))
                {
                    wasPreviousCharSeparator = false;
                    builder.Append(currentChar);
                }
                else if (wasPreviousCharSeparator == false)
                {
                    builder.Append(separator);
                    wasPreviousCharSeparator = true;
                }
                //if not valid - just skip it
            }

            //remove separator from begining and end
            return builder.ToString().Trim(separator).Trim('.');
        }
    }
}